import { ref } from 'vue';
import { ElMessageBox } from 'element-plus';
import { useCourseStore } from '@/store/kg/course';

// 课程store
const courseStore = useCourseStore();

// 用于删除的课程ID数组
export const deleteIds = ref<string[]>([]);
// 课程对话框的显示状态
export const courseDialogVisible = ref(false);
// 分配用户权限对话框的显示状态
export const assignUsersDialogVisible = ref(false);
// 分配前置课程对话框的显示状态
export const assignPrerequisitesDialogVisible = ref(false);
// 当前操作的课程ID
export const currentCourseId = ref<string>('');
// 当前正在编辑的课程对象
export const currentCourse = ref<any>({});
// 表单加载状态
export const formLoading = ref(false);
// 操作类型（新增/编辑）
export const operationType = ref<'add' | 'update'>('add');
// 分配用户加载状态的映射
export const switchLoadMap = ref<any>({});

/**
 * 搜索课程
 */
export const onSearch = async () => {
  await courseStore.getCourseList();
};

/**
 * 添加课程
 */
export const onAdd = () => {
  operationType.value = 'add';
  currentCourse.value = {};
  courseDialogVisible.value = true;
};

/**
 * 编辑课程
 */
export const onUpdate = (row: any) => {
  operationType.value = 'update';
  currentCourse.value = { ...row };
  currentCourseId.value = String(row.nodeId);
  courseDialogVisible.value = true;
};

/**
 * 删除课程
 */
export const onDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除课程 ${row.name} 吗？`, '删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await courseStore.deleteCourse(String(row.nodeId));
    onSearch();
  });
};

/**
 * 批量删除课程
 */
export const onDeleteBatch = () => {
  ElMessageBox.confirm(`确认删除选中的 ${deleteIds.value.length} 条数据吗？`, '批量删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const promises = deleteIds.value.map(id => courseStore.deleteCourse(id));
    await Promise.all(promises);
    onSearch();
  });
};

/**
 * 为课程分配授权用户
 */
export const onAssignUsersToCourse = (row: any) => {
  currentCourseId.value = String(row.nodeId);
  assignUsersDialogVisible.value = true;
};

/**
 * 分配前置课程
 */
export const onAssignPrerequisitesToCourse = (row: any) => {
  currentCourseId.value = String(row.nodeId);
  assignPrerequisitesDialogVisible.value = true;
};

/**
 * 保存课程表单
 */
export const onSaveCourse = async (formRef: any) => {
  if (!formRef) return;
  
  await formRef.validate(async (valid: boolean) => {
    if (!valid) return;
    
    formLoading.value = true;
    try {
      if (operationType.value === 'add') {
        await courseStore.createCourse(currentCourse.value);
      } else {
        await courseStore.updateCourse(currentCourseId.value, currentCourse.value);
      }
      courseDialogVisible.value = false;
      onSearch();
    } finally {
      formLoading.value = false;
    }
  });
}; 